package com.common.config;

import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import java.net.UnknownHostException;
import java.util.Arrays;

/**
 * @classDescription:
 * @author:xiayingjie
 * @createTime:16/8/16
 */
//@Configuration
//@EnableMongoRepositories("com.common.mongo")
public class Mongo1Config extends AbstractMongoConfiguration{
    //返回数据库 和直接声明一样，虽然没有显示定义MongoTemplate 但是还是会隐式创建
    @Override
    protected String getDatabaseName() {
        return "test";
    }
    //创建mongo的实例
    @Override
    public Mongo mongo() throws Exception {
        //可以设置端口和路径
        MongoClient mongo= new MongoClient("localhost",27017);
        return mongo;
    }

    //如果有账号密码
    public MongoClient auth() throws UnknownHostException {
        MongoCredential credential=MongoCredential.createCredential("username","database","password".toCharArray());
        return new MongoClient(new ServerAddress("localhost",27017), Arrays.asList(credential));
    }
}
